<script setup>
import { nextTick, onMounted, ref } from 'vue';
import CustomContentPadProvider from './designer/plugins/content-pad';
import CustomPaletteProvider from './designer/plugins/palette';
import Log from './Log';
import MyProcessDesigner from './designer/ProcessDesigner.vue';
import MyPropertiesPanel from './penal/PropertiesPanel.vue';
import ProcessViewer from './viewer/index.vue';

import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';

const emits = defineEmits(['save', 'update:modelValue']);
const props = defineProps({
  modelValue: String,
  flowData: {
    type: Object,
    default: () => {}
  },
  isViewer: {
    type: Boolean,
    default: false
  }
});

const xmlStr = ref(props.modelValue);
const bpmnModeler = ref(null);
const reloadIndex = ref(0);
const controlForm = ref({
  processId: '',
  processName: '',
  simulation: true,
  labelEditing: true,
  labelVisible: true,
  prefix: 'flowable',
  events: ['element.click', 'element.contextmenu'],
  additionalModel: [CustomContentPadProvider, CustomPaletteProvider]
});

onMounted(() => {});

const element = ref(null);
const elementClick = element => {
  element.value = element;
};

const elementContextmenu = element => {
  console.log('elementContextmenu:', element);
};

const initModeler = modeler => {
  nextTick(() => {
    bpmnModeler.value = modeler;
    const canvas = modeler.get('canvas');
    const rootElement = canvas.getRootElement();
    Log.prettyPrimary('Process Id:', rootElement.id);
    Log.prettyPrimary('Process Name:', rootElement.businessObject.name);
  });
};

const onSave = () => {
  emits('update:modelValue', xmlStr.value);
  emits('save', {
    xml: xmlStr.value
  });
};
</script>

<template>
  <div class="process-designer">
    <template v-if="!props.isViewer">
      <my-process-designer
        :key="`designer-${reloadIndex}`"
        ref="processDesigner"
        v-model="xmlStr"
        :options="{
          taskResizingEnabled: true,
          eventResizingEnabled: true
        }"
        keyboard
        v-bind="controlForm"
        @save="onSave"
        @element-click="elementClick"
        @element-contextmenu="elementContextmenu"
        @init-finished="initModeler"
      />
      <my-properties-panel
        :key="`penal-${reloadIndex}`"
        :bpmn-modeler="bpmnModeler"
        :prefix="controlForm.prefix"
        class="process-panel"
      />
    </template>
    <template v-else>
      <process-viewer :flowData="flowData" />
    </template>
  </div>
</template>

<style lang="scss" scoped>
.process-designer {
  display: flex;
  height: calc(100vh - 84px);
}
</style>
